import { findAttWorkingData, findAttOverData, findAttData } from '../../../api/attendance';

Page({
  data: {
    id: 0,
    name: '',
    currentDate: '',
    spotMap: {},
    changeTime: '',
    dateListMap: [],
    overtimeRecords: [],
    totalDays: 0,
    totalOvertimeHours: 0,
    isLoading: false // 添加加载状态
  },
  
  onLoad(options) {
    const { id, name } = options;
    if (id && name) {
      const parsedId = parseInt(id, 10);
      if (!isNaN(parsedId)) {
        const date = new Date().toISOString().slice(0, 7); 
        this.setData({
          id: parsedId,
          name,
          currentDate: date
        });
        this.fetchData(parsedId, date);
      } else {
        console.error('Invalid ID format');
      }
    } else {
      console.error('ID or name is missing in options');
    }
  },

  fetchData(id, date) {
    this.setData({ isLoading: true });
    Promise.all([
      this.fetchAttendanceData(id, date),
      this.fetchOvertimeData(id, date),
      this.fetchSummaryData(id, date)
    ]).then(() => {
      this.setData({ isLoading: false });
    }).catch(() => {
      this.setData({ isLoading: false });
    });
  },

  fetchAttendanceData(id, date) {
    return new Promise((resolve, reject) => {
      findAttWorkingData(id, date).then(response => {
        if (response.code === 1) {
          const spotMap = {};
          response.data.forEach(item => {
            const key = `y${item.time.split('-')[0]}m${item.time.split('-')[1]}d${item.time.split('-')[2]}`;
            spotMap[key] = item.data === 1 ? 'blue-spot' : (item.data === 0.5 ? 'yellow-spot' : '');
          });
          
          this.setData({
            spotMap,
            currentDate: date
          });
          resolve();
        } else {
          console.error('Failed to fetch attendance data');
          reject();
        }
      }).catch(error => {
        console.error('Error fetching attendance data:', error);
        reject();
      });
    });
  },

  fetchOvertimeData(id, date) {
    return new Promise((resolve, reject) => {
      findAttOverData(id, date).then(response => {
        if (response.code === 1) {
          const overtimeRecords = response.data.map(item => ({
            date: item.time,
            hours: item.data
          }));
          this.setData({
            overtimeRecords
          });
          resolve();
        } else {
          console.error('Failed to fetch overtime data');
          reject();
        }
      }).catch(error => {
        console.error('Error fetching overtime data:', error);
        reject();
      });
    });
  },

  fetchSummaryData(id, date) {
    return new Promise((resolve, reject) => {
      findAttData(id, date).then(response => {
        if (response.data) {
          const workingTimes = response.data.workingTimes !== undefined ? response.data.workingTimes : 0;
          const overTimes = response.data.overTimes !== undefined ? response.data.overTimes : 0;
          this.setData({
            totalDays: workingTimes,
            totalOvertimeHours: overTimes
          });
          resolve();
        } else {
          this.setData({
            totalDays: 0,
            totalOvertimeHours: 0
          });
          resolve();
        }
      }).catch(error => {
        console.error('Error fetching summary data:', error);
        this.setData({
          totalDays: 0,
          totalOvertimeHours: 0
        });
        reject();
      });
    });
  },

  onDateChange(event) {
    const { currentDate } = event.detail;
    this.setData({
      currentDate: currentDate,
      totalDays: 0,
      totalOvertimeHours: 0,
      overtimeRecords: []
    });
    this.fetchData(this.data.id, currentDate);
  }
});
